package com.liyao.windowtest4.controller;

import com.liyao.windowtest4.Utils.SharedModel;
import com.liyao.windowtest4.pojo.torqueRow;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import javafx.util.converter.NumberStringConverter;

import java.net.URL;
import java.util.ResourceBundle;

/**
 * @program: windowtest4
 * @description:
 * @author: liu yan
 * @create: 2024-10-24 15:09
 */
public class torqueProgramController implements Initializable {
    @FXML
    public TextField TorqueMin;
    public TextField AngleTarget;
    public TextField TorqueMax;
    public TextField AngleMin;
    public TextField TorqueTarget;
    public TextField AngleMax;
    public TextField StartAngle;



    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        setNumericTextFormatter(TorqueMin);
        setNumericTextFormatter(AngleTarget);
        setNumericTextFormatter(TorqueMax);
        setNumericTextFormatter(AngleMin);
        setNumericTextFormatter(TorqueTarget);
        setNumericTextFormatter(AngleMax);
        setNumericTextFormatter(StartAngle);
//        torqueRow newData = new torqueRow(); // 创建新数据
//        EventBusSingleton.getEventBus().post(new DataUpdateEvent(newData));
    }

    private void setNumericTextFormatter(TextField textField) {
        StringConverter<Number> converter = new NumberStringConverter();
        textField.setTextFormatter(new TextFormatter<>(converter, 0, (change) -> {
            if (change.isContentChange()) {
                String text = change.getControlNewText();
                if (text.matches("-?\\d+(\\.\\d*)?|(\\.?)$")) {
                    return change;
                }
            }
            return null; // 拒绝不符合格式的更改
        }));
    }

    @FXML
    public void SaveTorque(ActionEvent actionEvent) {
        boolean isValid = true;

        isValid &= !isTextFieldEmptyOrWhitespace(TorqueMin, "扭矩下限不能为空");
        isValid &= !isTextFieldEmptyOrWhitespace(AngleTarget, "目标角度不能为空");
        isValid &= !isTextFieldEmptyOrWhitespace(TorqueMax, "扭矩上限不能为空");
        isValid &= !isTextFieldEmptyOrWhitespace(AngleMin, "最小角度不能为空");
        isValid &= !isTextFieldEmptyOrWhitespace(TorqueTarget, "目标扭矩不能为空");
        isValid &= !isTextFieldEmptyOrWhitespace(AngleMax, "角度上限不能为空");
        isValid &= !isTextFieldEmptyOrWhitespace(StartAngle, "贴合扭矩不能为空");

        if (isValid) {
            double TorqueMinText=Double.parseDouble(TorqueMin.getText());
            double AngleTargetText=Double.parseDouble(AngleTarget.getText());
            double TorqueMaxText=Double.parseDouble(TorqueMax.getText());
            double AngleMinText=Double.parseDouble(AngleMin.getText());
            double TorqueTargetText=Double.parseDouble(TorqueTarget.getText());
            double AngleMaxText=Double.parseDouble(AngleMax.getText());
            double StartAngleText=Double.parseDouble(StartAngle.getText());
            ObservableList<torqueRow> data = SharedModel.getInstance().getTableData();

            //torqueRowIntegerCellDataFeatures.getTableView().getItems().indexOf(torqueRowIntegerCellDataFeatures.getValue()) + 1
            torqueRow newData = new torqueRow(TorqueMinText,AngleTargetText,TorqueMaxText,AngleMinText,TorqueTargetText,AngleMaxText,StartAngleText); // 创建新数据
            data.add(newData);
        }
    }

    /**
     * 检查TextField是否为空或仅包含空白字符。
     *
     * @param textField 要检查的TextField
     * @param errorMessage 如果TextField为空，则显示的错误消息（这个参数主要用于调试或更详细的用户反馈）
     * @return 如果TextField为空或仅包含空白字符，则返回true；否则返回false
     */
    private boolean isTextFieldEmptyOrWhitespace(TextField textField, String errorMessage) {
        String text = textField.getText().trim();
        if (text.isEmpty()) {
            showAlert(Alert.AlertType.ERROR,"验证错误", "请填写所有必填项",errorMessage);
            System.err.println(errorMessage);
            return true;
        }
        return false;
    }

    /**
     * 显示一个Alert对话框。
     *
     * @param alertType Alert的类型（如ERROR, INFORMATION, WARNING, CONFIRMATION）
     * @param title Alert的标题
     * @param headerText Alert的头部文本
     */
    private void showAlert(Alert.AlertType alertType, String title, String headerText,String ContentText) {
        Alert alert = new Alert(alertType);
        alert.setTitle(title);
        alert.setHeaderText(headerText);
        alert.setContentText(ContentText); // 可以根据需要自定义内容文本
        alert.showAndWait(); // 显示对话框并等待用户响应
    }


    @FXML
    public void handleSaveAndClose(ActionEvent actionEvent) {
        boolean isValid = true;

        isValid &= !isTextFieldEmptyOrWhitespace(TorqueMin, "扭矩下限不能为空");
        isValid &= !isTextFieldEmptyOrWhitespace(AngleTarget, "目标角度不能为空");
        isValid &= !isTextFieldEmptyOrWhitespace(TorqueMax, "扭矩上限不能为空");
        isValid &= !isTextFieldEmptyOrWhitespace(AngleMin, "最小角度不能为空");
        isValid &= !isTextFieldEmptyOrWhitespace(TorqueTarget, "目标扭矩不能为空");
        isValid &= !isTextFieldEmptyOrWhitespace(AngleMax, "角度上限不能为空");
        isValid &= !isTextFieldEmptyOrWhitespace(StartAngle, "贴合旧居不能为空");

        if (isValid) {
            double TorqueMinText=Double.parseDouble(TorqueMin.getText());
            double AngleTargetText=Double.parseDouble(AngleTarget.getText());
            double TorqueMaxText=Double.parseDouble(TorqueMax.getText());
            double AngleMinText=Double.parseDouble(AngleMin.getText());
            double TorqueTargetText=Double.parseDouble(TorqueTarget.getText());
            double AngleMaxText=Double.parseDouble(AngleMax.getText());
            double StartAngleText=Double.parseDouble(StartAngle.getText());
            ObservableList<torqueRow> data = SharedModel.getInstance().getTableData();
            torqueRow newData = new torqueRow(TorqueMinText,AngleTargetText,TorqueMaxText,AngleMinText,TorqueTargetText,AngleMaxText,StartAngleText); // 创建新数据
            data.add(newData);
            Stage stage = (Stage) ((Button) actionEvent.getSource()).getScene().getWindow();
            // 关闭窗口
            stage.close();
        }
    }

    @FXML
    public void CloseWindow(ActionEvent actionEvent) {
        Stage stage = (Stage) ((Button) actionEvent.getSource()).getScene().getWindow();
        // 关闭窗口
        stage.close();
    }
}
